/* 
 * File: timespan.cpp
 * Project: QTimeTracker
 * Author: Steve Sindelar, http://stevesindelar.cz
 * Licence: NewBSD licence.
 */
#include "timespan.h"
#include "timespandata.h"

using namespace Qt;
using namespace Core;

TimeSpan::TimeSpan()
{
}

TimeSpan::TimeSpan(const TimeSpan& span)
{
    this->from = span.from;
    this->finished = span.finished;
    this->length = span.length;
}

bool TimeSpan::isRunning() const
{
    return !this->finished;
}

QDateTime& TimeSpan::zeroDate()
{
    static QDateTime result(QDate(0,0,0), QTime(0,0), TimeSpec::UTC);
    return result;
}


void TimeSpan::start()
{
    this->from = QDateTime::currentDateTime();
    this->finished = false;
}

void TimeSpan::stop()
{
    if (this->finished)
    {
        throw std::exception("can't stop TimeSpan twice");
    }
    this->length = this->_getLength();
    this->finished = true;
}




QDateTime TimeSpan::_getLength() const
{
    if (!this->finished)
    {
        long secs = this->from.secsTo(QDateTime::currentDateTime());
        return zeroDate().addSecs(secs);
    }
    return this->length;
}

TimeSpanData TimeSpan::getLength() const
{
    long secs = zeroDate().secsTo(this->_getLength());
    return TimeSpanData::fromSeconds(secs);
}

void TimeSpan::setLength(int hours, int minutes, int seconds)
{
    this->finished = true; 
    this->length = zeroDate().addSecs(hours*60*60 + minutes*60 + seconds);
}




QDateTime TimeSpan::getFrom() const
{
    return this->from;
}

void TimeSpan::setFrom(QDateTime val)
{
    if (this->finished)
    {
        this->length = this->length.addSecs(-this->from.secsTo(val)); //recount seconds.
    }
    this->from = val;
}


QDateTime TimeSpan::getTo() const
{
    return this->from.addSecs(this->getLength().getSecs());
}

void TimeSpan::setTo(QDateTime val)
{
    long secs = this->from.secsTo(val);
    QDateTime length = zeroDate();
    this->length = length.addSecs(secs);
}

